package com.michael.retail.auth.controller;

import com.google.code.kaptcha.Producer;
import com.michael.retail.auth.service.ValidCodeService;
import com.michael.retail.commons.pojo.global.R;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码提供
 *
 * @author zlt
 * @date 2018/12/18
 */
@Controller
@RequestMapping("/valid")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ValidCodeController {

    private final Producer producer;
    private final ValidCodeService validCodeService;

    /** 图形验证码 */
    @GetMapping("/pic/{requestId}")
    public void picValidCode(@PathVariable String requestId, HttpServletResponse response) throws IOException {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);

        validCodeService.setServerValidCode(requestId, text);

        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "JPEG", out);
        }
    }

    /** 手机验证码 */
    @GetMapping("/mobile/{deviceId}")
    public R mobileValidCode(@PathVariable String deviceId) {
        // 手机验证码频次限制
        // 发送短信...
        // 保存至服务器用于校验
        System.out.println(deviceId);

        return R.succeed();
    }
}
